/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.asseco.mio.core.webapp.controller;

import com.asseco.mio.codex.Country;
import com.asseco.persistence.service.HibernateUtil;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.annotate.JsonValue;
import org.codehaus.jackson.*;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author gjoko.mitrovski
 */
@Controller
@RequestMapping("/autocomplete*")
public class AutoComplete {

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView handleRequest(@RequestParam(required = false, value = "q") String query, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        query = "%";
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Country.class).add(Restrictions.like("name", "%" + query + "%")).setMaxResults(5);

        List result = criteria.list();
        session.getTransaction().commit();
        List nameList = new ArrayList();
        for (int i = 0; i < result.size(); i++) {
            Country element = (Country) result.get(i);
            if (element != null) {
                nameList.add(element.getName());
            }
        }

//                List myList1 = new ArrayList();
//        myList1.add("Liberia");
//        myList1.add("Lybia");

        JSONArray jsonArrayNames = new JSONArray(nameList);
        System.out.println("jsonArray " + jsonArrayNames.join(","));

        List idList = new ArrayList();
        for (int i = 0; i < result.size(); i++) {
            Country element = (Country) result.get(i);
            if (element != null) {
                idList.add(element.getId());
            }
        }

        JSONArray jsonArrayId = new JSONArray(idList);
        System.out.println("jsonArray " + jsonArrayId.join(","));
//        Map map = new HashMap();
//        map.put("beanlist", "1");
//        map.put("beanlist2", "2");

//JSONObject jsonObject = new JSONObject(map);


//System.out.println("==== json :"+jsonObject.toString());

        return new ModelAndView();
    }
}
